package com.adcc.ags.gms.mq.service;

import com.adcc.ags.gms.core.entity.GWLogLevel;
import com.adcc.ags.gms.core.util.AppConfiguration;
import com.adcc.ags.gms.core.util.Constant;
import com.adcc.ags.gms.core.util.LogFactory;
import com.adcc.ags.gms.core.util.MQFactory;
import com.adcc.ags.gms.gw.service.SysConfigurationService;
import com.adcc.ags.gms.mq.vo.QMVO;
import com.adcc.utility.mq.entity.ibm.QueueManager;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 消息管理器服务层
 */
@Service("QMService")
public class QMServiceImpl implements QMService {

    @Autowired
    private LogFactory log;

    @Autowired
    private AppConfiguration appConfiguration;

    @Autowired
    private MQFactory mqFactory;

    @Autowired
    private SysConfigurationService configurationService;

    @Override
    public Optional<List<QMVO>> getAllQMByPCF() {
        List<QMVO> result = Lists.newArrayListWithExpectedSize(10);
        try {
            List<QueueManager> list = mqFactory.getSourceMQM().findQueueManager();
            if (list != null && list.size() > 0) {
                int intConns = Integer.valueOf(configurationService.getValue(Constant.MQ_QM_CONNS));
                for (QueueManager qm : list) {
                    QMVO vo = new QMVO(qm);
                    if(qm.getConnectCount() > intConns){
                        log.warn(QMService.class,"MQ","QM:" + vo.getName() + "连接数超过告警阀值");
                        vo.setOverflow(true);
                    }
                    result.add(vo);
                }
            } else {
                log.error(QMService.class,"MQ",GWLogLevel.SERIOUS_ALARM, "消息队列管理器:" + appConfiguration.getSourceMQQM() + "已停止");
                QMVO vo = new QMVO();
                vo.setName(appConfiguration.getSourceMQQM());
                vo.setIp(appConfiguration.getSourceMQIP());
                vo.setPort(appConfiguration.getSourceMQPort());
                vo.setStartTime("");
                vo.setConnectCount(0);
                vo.setStatus("Stop");
                result.add(vo);
            }
            return Optional.of(result);
        } catch (Exception ex) {
            log.error(QMService.class,"MQ",GWLogLevel.SERIOUS_ALARM, "消息队列管理器:" + appConfiguration.getSourceMQQM() + "已停止",ex);
            QMVO vo = new QMVO();
            vo.setName(appConfiguration.getSourceMQQM());
            vo.setIp(appConfiguration.getSourceMQIP());
            vo.setPort(appConfiguration.getSourceMQPort());
            vo.setStartTime("");
            vo.setConnectCount(0);
            vo.setStatus("Stop");
            result.add(vo);
            return Optional.of(result);
        }
    }
}
